package com.idc.config.security.login.username_password;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author Trump
 * @version 1.0.0
 * @ClassName UsernamePasswordAuthenticationProvider.java
 * @Description 手机验证码登录
 * @createTime 2019年08月15日 11:09:00
 */
public class UsernameAuthenticationProvider implements AuthenticationProvider {
    protected Log logger = LogFactory.getLog(getClass());


    @Qualifier("")
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        UsernameAuthenticationToken tokenReq = (UsernameAuthenticationToken) authentication;

        //todo 根据手机号码，查找登录人信息....
        UserDetails userDetails = userDetailsService.loadUserByUsername(tokenReq.getLoginAcct());

        //todo 密码加密后比较是否匹配
        if(!passwordEncoder.matches(tokenReq.getPassword(), userDetails.getPassword())) {
            throw new BadCredentialsException("用户名密码不匹配");
        }
        return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (UsernameAuthenticationToken.class.isAssignableFrom(authentication));
    }

}
